package com.sky.service.admin.impl;

import cn.hutool.core.date.DateException;
import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.autoFill.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.enumeration.OperationType;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.EmployeeNameExistException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.admin.EmployeeMapper;
import com.sky.pojo.Employee;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.admin.EmployeeService;
import com.sky.vo.EmployeeVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) throws UnsupportedEncodingException {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();//

        //1、根据用户名查询数据库中的数据  select * from employee where username = #{username}
        Employee employee = employeeMapper.getByUsername(username); //

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes("UTF-8"));
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        //3、返回实体对象
        return employee;
    }

    //新增员工
    @Override
    public void save(EmployeeDTO dto) throws UnsupportedEncodingException {
        if (null == dto || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getSex()) ||
                StringUtils.isEmpty(dto.getUsername()) || StringUtils.isEmpty(dto.getPhone()) ||
                StringUtils.isEmpty(dto.getIdNumber())) {
            throw new DateException(MessageConstant.DATA_ERROR);
        }
        Employee emp = new Employee();
        Employee byUsername = employeeMapper.getByUsername(dto.getUsername());
        if (byUsername != null) {
            throw new EmployeeNameExistException(dto.getUsername() + "已经存在");
        }
        BeanUtils.copyProperties(dto, emp);
        emp.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes("UTF-8")));
        emp.setStatus(StatusConstant.ENABLE);
        employeeMapper.save(emp);
    }
    //分页查询
    @Override
    public PageResult pageFind(EmployeePageQueryDTO employeePageQueryDTO) {
        if (employeePageQueryDTO.getPage() < 0 || employeePageQueryDTO.getPageSize() > 100) {
            employeePageQueryDTO.setPage(1);
        }
        if (employeePageQueryDTO.getPageSize() < 0 || employeePageQueryDTO.getPageSize() > 100) {
            employeePageQueryDTO.setPageSize(10);
        }
        Page<Employee> page = PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        employeeMapper.pageFind(employeePageQueryDTO.getName());
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    //修改员工状态
    @Override
    public Result<String> updateType(Integer status, Long id) {
        int count = employeeMapper.updateType(status, id);
        return count == 1 ? Result.success() : Result.error("状态更新失败");
    }
    //根据ID查询员工
    @Override
    public EmployeeVO selectById(Long id) throws CloneNotSupportedException {
        Employee employee = employeeMapper.selectById(id);

        return employee.clone();
    }

    //修改员工
    @Override
    public Result update(EmployeeDTO dto) throws CloneNotSupportedException {
        Employee employee = dto.clone();
        employee.setUpdateUser(BaseContext.getCurrentId());
        int count = employeeMapper.update(employee);
        return count == 1 ? Result.success() : Result.error("更新失败");
    }


}
